<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\Props
 *
 * @property int $props_id
 * @property string $name 属性名称
 * @property int $sort 排序的序号
 * @property int $disabled 是否删除 0-否 1-是
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Props whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Props whereDisabled($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Props whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Props wherePropsId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Props whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Props whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Props extends Model
{
    protected $table = 'props';
    protected $primaryKey = 'props_id';

    protected $guarded = [];

    public static $error ;

    /**属性的添加或者更新
     * @param $data
     * @return bool 成功返回true 失败返回false
     */
    public function store($data)
    {
        if(empty($data['Rule']['rule_id'])){
            return $this->add($data);
        }
        return $this->edit($data);
    }

    /**属性的添加
     * @param $post  array 提交过啦的表单数据
     * @return bool  成功返回true 失败返回false
     */
    public function add($post)
    {
        unset($post['Rule']['rule_id']);
        //向属性表数据中添加数据
        $prop_model = $this -> create($post['Rule']);

        //向属性值表中添加数据
        $res = $this->insert_value($prop_model -> props_id,$post);
        if(!$res){
            self::$error = '插入属性值表失败';
            return false;
        }
        return $prop_model->props_id;
    }

    /**属性的删除
     * @param $post  array 提交过啦的表单数据
     * @return bool  成功返回true 失败返回false
     */
    public function del($props_id)
    {
        $props_model = Props::find($props_id);
        $props_val_model = new PropsVal();

        if(!empty($props_model)){
            //删除属性
            $props_model -> disabled = '1';
            $props_model -> save();

            //删除属性下面的值
            PropsVal::where('props_id',$props_id)->update(
                ['disabled'=>'1']
            );
        }
        return true;
    }

    /**属性的编辑
     * @param $post  array 提交过啦的表单数据
     * @return bool  成功返回true 失败返回false
     */
    public function edit($post)
    {
        $props_id = $post['Rule']['rule_id'];
        $new_value_arr = [
            'Val'=>[
                'val_name' => isset($post['Val']['val_name'])?$post['Val']['val_name']:[],
                'sort'     => isset($post['Val']['sort'])?$post['Val']['sort']:[]
            ]
        ];
        unset($post['Rule']['rule_id'],$post['Val']['val_name'],$post['Val']['sort']);

        $props_model = $this->find($props_id);
        if(!empty($props_model)){

            //对属性表的数据更新
            $props_model->name = $post['Rule']['name'];
            $props_model->sort = $post['Rule']['sort'];
            if($props_model->save()){

                //查出该属性关联的所有属性值id
                $db_value_id_arr = PropsVal::query()
                    ->select('props_val_id')
                    ->where(['props_id'=>$props_id,'disabled'=>'0'])
                    ->get()->toArray();
                $db_value_id_arr = array_column($db_value_id_arr,'props_val_id');
                $del_value_id_arr = empty($post['Val']) ? $db_value_id_arr : del_arr(array_keys($post['Val']),$db_value_id_arr);
                if(!empty($del_value_id_arr)){

                    //有需要删除的属性值id
                    PropsVal::query()->whereIn('props_val_id',$del_value_id_arr)->update(['disabled'=>1]);
                }

                //没有需要删除的原有属性值
                //更新原有属性值的数据
                if(!empty($post['Val'])){
                    foreach($post['Val'] as $old_value_arr){
                        $val_id = $old_value_arr['val_id'];
                        unset($old_value_arr['val_id']);
                        PropsVal::query()
                            ->where('props_val_id',$val_id)
                            ->update($old_value_arr);
                    }
                }

                //插入行的属性值书局
                self::insert_value($props_id,$new_value_arr);
                return $props_id;
            }

            self::$error = '更新属性值表失败';
            return false;
        }
        return true;
    }

    /**
     * 获取格式化好的属性-值列表
     */
    public function getProplist()
    {
        $pro_val_list = [];
        $props_list = $this->newQuery()
            ->select('props_id')
            ->distinct()
            ->where(['disabled'=>'0'])
            ->get();
        foreach($props_list as $props){
            $val_list = PropsVal::query()
                -> select('props_val_id AS props_value_id','name AS val_name')
                -> where(['props_id'=>$props['props_id'],'disabled'=>'0'])
                -> get()
                -> toArray();
            $pro_val_list[] = [
                'props_id'  => $props['props_id'],
                'prop_name' => Props::find($props['props_id'])->name,
                'val_list'  => $val_list
            ];
        }

        return $pro_val_list;
    }


    /**根据获取的props_id 向属性值表中插入数据
     * @param $props_id
     * @return bool|int
     */
    public function insert_value($props_id,$post)
    {
        $insert_data = [];
        if(isset($post['Val']) && !empty($post['Val']['val_name'])){
            foreach($post['Val']['val_name'] as $k => $v){
                $insert_data[] = [
                    'updated_at'=>Carbon::now(),'created_at'=>Carbon::now(),'props_id'=>$props_id,'name'=>$v,'sort'=>$post['Val']['sort'][$k],
                ];
            }
            //更新propsVal表的数据
            return PropsVal::insert($insert_data);
        }
        return true;
    }
}
